/**
 * @Description: activityDetailView.jsx
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Row, Col, Card, Button, Tabs, Form, Popconfirm, Modal,Input } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
// 当前组件样式
import styles from './orderListStyle.less'
import { Grid, QueryCondition } from 'widget/Grid/index'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import Keypress  from 'widget/Keypress'
import { chunk,isEmpty } from 'lodash'
import FlagBtn from 'widget/FlagBtn/FlagView'

const FormItem = Form.Item
const { TextArea } = Input
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
// 支付状态：1，未支付，2，已支付，3支付超时，8，待退款，9已退款
let statusMap = {
  1: {
    value: '1',
    label: '待支付'
  },
  2: {
    value: '2',
    label: '已支付'
  },
  3: {
    value: '3',
    label: '支付超时'
  },
  8: {
    value: '8',
    label: '待退款'
  },
  9: {
    value: '9',
    label: '已退款'
  },
}
let productTypeMap={//商品类型
  1:'房源',
  2:'停车位',
  3:'商铺',
  4:'日用快消',
  5:'家电数码',
  6:'首饰箱包',
  7:'其他'
}
let propertyTypeMap={//物业类型
  11:'住宅',
  12:'公寓',
  21:'地上车位',
  22:'地下车位（非人防车位',
  23:'地下车位（人防车位）',
  24:'地下车库',
  25:'地上车库',
  31:'地上商铺',
  32:'地下商铺',
  33:'地上集中商业',
  34:'地下集中商业',
}
let productTypeLabelMap = { 1: '详细房号', 2: '车位位置', 3: '商铺位置',4:'商品名称',5:'商品名称',6:'商品名称',7:'商品名称' }
const TabPane = Tabs.TabPane
const routeView = function ({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const {modelObj, namespace} = model
  let {loading, btnLoading, modalObj, currentItem, queryList, tableData, pageConfig,rewardModal,rewardObj} = modelObj
  // modelObj.xxx获取model中状态机的值
  console.log('modelObj', modelObj)
  // 点击处理事件
  const clickHandler = (e) => {
    // 分发到model文件中effects的xxx方法
    dispatch({
      type: `${namespace}/xxx`,
      payload: {}
    })
  }


  // 订单编号 seckillOrderId  项目名称 projectName 类型 productType  详情 detail  活动名称 activeName 订单类型 orderTyp 状态 status 客户姓名 accountName  创建订单时间
  const columns = [
    {
      title: '订单编号', dataIndex: 'seckillOrderId', key: 'seckillOrderId',
    },
    {title: '项目名称', dataIndex: 'projectName', key: 'projectName'},
    {title: '详情', dataIndex: 'detail', key: 'detail'},
    {title: '活动名称', dataIndex: 'activeName', key: 'activeName'},
    {
      title: '订单类型', dataIndex: 'orderType', key: 'orderType',width:100,//
      render: function (value, item, index) {
        return <span>{{1:'报名费',2:'订金',}[value]}</span>
      }
    },
    {
      title: '支付状态', dataIndex: 'status', key: 'status',width:80,//1:未上架，2已上架，3解除
      render: function (value, item, index) {
        return (<span>{(statusMap[value]||{}).label}</span>)
      }
    },
    {title: '客户昵称', dataIndex: 'accountName', key: 'accountName',width:100},
    {title: '客户手机', dataIndex: 'accountMobile', key: 'accountMobile',width:100},
    {title: '创建订单时间', dataIndex: 'createTime', key: 'createTime',width:180},
    {
      title: '兑奖方式', dataIndex: 'receiveWay', key: 'receiveWay',width:100,//
      render: function (value, item, index) {
        return <span>{{1:'项目现场兑奖',2:'邮寄',}[value]}</span>
      }
    },
    {title: '收货姓名', dataIndex: 'receiveName', key: 'receiveName',width:100},
    {title: '收货手机', dataIndex: 'receiveMobile', key: 'receiveMobile',width:100},
    {title: '收货地址', dataIndex: 'detailAddress', key: 'detailAddress',width:180},
    {title: '是否兑奖', dataIndex: 'confirmStatus', key: 'confirmStatus',width:100,
      render: function (value, item, index) {
        if(value){
          return <span>{{1:'是',2:'否'}[value]}</span>
        }else{
          return <span>否</span>
        }
        
      }
    },
    {title: '兑奖人', dataIndex: 'updatePerson', key: 'updatePerson',width:100},
    {title: '备注', dataIndex: 'remark', key: 'remark',width:200},
  ]
  // 表格模板配置
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: [].concat(columns, generateAction()),
      pageConfig, tableData
    },
    pageChange: (pageNo, pageSize) => {
      console.log(pageNo, pageSize)
      dispatch({ type: `${namespace}/pageChange`, payload: {pageNo, pageSize } });
    },
    scroll: {x: 2000},
    loading
  }

  // 表格操作区域
  function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 80,
      render: (data, record, index) => {
        return (
          <span>
             <FlagBtn
                 node={ <a onClick={() => updateModal({item: record, index})}>详情<span className="ant-divider" /></a>}
                 btnId={'90601'}
             >
                </FlagBtn>
            { (record.status == "2" && (!record.confirmStatus || record.confirmStatus!='1')) &&
              <FlagBtn node={<a onClick={() => { changeRewardModal('1',record.seckillOrderId)}}>兑奖<span className="ant-divider" /></a>} > </FlagBtn>
            }
            { (record.status == "2" && (record.confirmStatus && record.confirmStatus=='1')) &&
              <FlagBtn node={<a onClick={() => { changeRewardModal('2',record.seckillOrderId)}}>取消兑奖<span className="ant-divider" /></a>} > </FlagBtn>
            }
          </span>
        )
      }
    }
  }

  //兑奖弹窗
  function changeRewardModal(confirmStatus,seckillOrderId){//1.兑奖 2.取消兑奖
    rewardObj.confirmStatus = confirmStatus;
    rewardObj.seckillOrderId = seckillOrderId;
    dispatch({
      type:`${namespace}/updateStore`,
      payload:{
        rewardModal:!rewardModal,
        rewardObj
      }
    })
  }

  // 详情页跳转
  function routerGo ({type, item = {}}) {
    let urlArray = MODULE_TO_ROUTES[namespace].urlArray
    hashHistory.push({
      pathname: urlArray[0],
      query: {pageType: type, id: item.seckillProductId || ''}
    })
  }

  // 弹窗
  function updateModal ({item, index} = {}) {
    modalObj.visible = !modalObj.visible
    currentItem = item
    console.log('updateModal', item, index)
    changeState({modalObj})
    if (item) {
      dispatch({
        type: `${namespace}/getDetail`,
        payload: {id: item.seckillOrderId, index}
      })
    }
  }

  // 详情
  function handleDetailList () {
    // ﻿项目名称 projectName  商品类型 productType  详细房号 detail  面积  area 户型 houseTypeName 户型朝向 orientation 物业类型 propertyType  竞拍标签 tags  起拍价 initPrice  原价 originalPrice  应付报名费 securityMoney  应付定金 earnestMoney  优惠价 平方价 squarePrice  成交价 myPrice  已交定金 earnestMoney  客户姓名 联系方式 mobile
    let list = []
    let keys = [
      {
        name: '项目名称',
        value: currentItem['projectName'] || '',
      },
      {
        name: '商品类型',
        value: productTypeMap[currentItem['productType']||''],
      },
      {
        name: productTypeLabelMap[currentItem['productType']||''],
        value: currentItem['detail'],
      },
      {
        name: '面积',
        value: currentItem['area'],
      },
      {
        name: '户型',
        value: currentItem['houseTypeName'],
      },
      {
        name: '户型朝向',
        value: currentItem['orientation'],
      },
      {
        name: '物业类型',
        value: propertyTypeMap[currentItem['propertyType']||''],
      },
      {
        name: '竞拍标签',
        value: (currentItem['tags']||[]).join(' '),
      },
      {
        name: '起拍价',
        value: currentItem['initPrice'],
      },
      {
        name: '加价幅度',
        value: currentItem['grads'],
      },
      {
        name: '报名费',
        value: currentItem['securityMoney'],
      },
      {
        name: '定金',
        value: currentItem['earnestMoney'],
      },
/*      {
        name: '优惠价',//原价-起拍价
        value: currentItem['salePrice'],
      },
      {
        name: '平方价',//
        value: currentItem['squarePrice'],
      },*/
      {
        name: '成交价',//定金类型才有成交价
        value: currentItem.orderType==2?currentItem['myPrice']:'',
      },
      {
        name: '客户姓名',//
        value: currentItem['name'],
      },
      {
        name: '联系方式',//
        value: currentItem['mobile'],
      },
      {
        name: '身份证号',//
        value: currentItem['cardNo'],
      },
    ]
    if(currentItem.productType==4){//其他商品类型，不显示户型和户型朝向、面积等
      keys.splice(3,4)
    }else if(currentItem.productType!=1){//非房源类型，不显示户型和户型朝向
      keys.splice(4,2)
    }
    if(currentItem.productType>3){//非日用品等其他
      keys.splice(3,4)
      keys.splice(7,1)
    }
    list = chunk(keys, 2)
    currentItem.list = list
  }

  handleDetailList()

  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  //修改状态
  const inputChange = (payload) => {
    let {key, value} = payload
    dispatch({
      type: `${namespace}/inputChange`,
      payload: {
        ...payload
      }
    })
  }
  //查询
  const onSearch = (payload) => {
    dispatch({
      type: `${namespace}/search`,
      payload: payload
    })
  }
  const queryReset = (payload) => {
    dispatch({
      type: `${namespace}/queryReset`,
      payload: payload
    })
  }


  return (
    <div className={cx('pageLayout')}>
      {/*监控键盘事件，自动刷新数据*/}
      <Keypress keyCode={13} cbk={()=>{
        onSearch();
      }} />
      <div className="public_listMain">
        <div className="functionButton">
          {/*<Button type="primary" loading={modelObj.exportLoading} onClick={() =>{}}>导出订单</Button>*/}
        </div>
        <AdvanceSearch
          footer={
            <span>
                <Button type="primary" htmlType="submit" onClick={() => onSearch()} loading={modelObj.loading}>搜索</Button>
                <Button onClick={() => dispatch({ type: `${namespace}/queryReset` })}>重置</Button>
              </span>
          }
        >
          <QueryCondition
            data={queryList}
            inputChange={(key, value) => dispatch({type: `${namespace}/inputChange`, payload: {key, value}})}
          />
        </AdvanceSearch>
        {/* 表格区域 */}
        <div className="boxShadow">
          {/* 搜索条件 */}

          {/* 添加用户 */}
          <Grid {...gridProps} />
        </div>
        <Modal
          title={'详情'}
          width='800px'
          // className="pubBiz_CommonModel"
          visible={modalObj.visible}
          onCancel={() => {updateModal()}}
          footer={null}
        >
          <div className={styles.detailContainer}>
            <table>
              <tbody className={'ant-table-tbody'}>
              {
                currentItem.list.map((item,idx) => {
                  let item_0 = item[0] || {}
                  let item_1 = item[1] || {}
                  return (
                    <tr key={idx}>
                      <td>{item_0.name}</td>
                      <td>{item_0.value}</td>
                      <td>{item_1.name}</td>
                      <td>{item_1.value}</td>
                    </tr>
                  )
                })
              }
              </tbody>
            </table>
          </div>
        </Modal>
        <Modal 
          title={'兑换操作'}
          visible={rewardModal}
          onCancel={() => { changeRewardModal(rewardObj.confirmStatus,rewardObj.seckillOrderId) }}
          onOk={(e) => {
            dispatch({
              type: `${namespace}/seckillOrderRedeem`,
              payload: {rewardObj}
            });
            changeRewardModal(rewardObj.confirmStatus,rewardObj.seckillOrderId);
          }}
        > 
          提示：
            <div>{'1'==rewardObj.confirmStatus?'确认已兑奖':'取消兑奖'}</div>
         <FormItem
            label="兑奖备注">
            {getFieldDecorator(`remark`, {
                  initialValue: rewardObj.remark||'',
                  rules: [
                    {  required: false,  message: '请输入备注信息'}
                  ],
                })(
                  <TextArea
                    onChange={ e =>{remarkChange(e.target.value,'remark')}}
                    // autoSize={{ minRows: 3, maxRows: 5 }}
                  />
                )}
              
            </FormItem>
        </Modal>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))

